package response

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"gitee.com/linxing_3/youye-core/sdk/pkg"
)

// GenerateMsgIDFromContext 生成msgID
func GenerateMsgIDFromContext(c IRespWriter) string {
	requestId := c.GetHeader(pkg.TrafficKey)
	if requestId == "" {
		requestId = uuid.New().String()
		c.SetHeader(pkg.TrafficKey, requestId)
	}
	return requestId
}

// Error 失败数据处理
func Error(c IRespWriter, code int, err error, msg string) {
	ErrorData(c, code, err, msg, nil)
}

// Error 失败数据处理
func ErrorData(c IRespWriter, code int, err error, msg string, data interface{}) {

	res := NewResponse().
		SetCode(code).
		SetTraceID(GenerateMsgIDFromContext(c)).
		SetSuccess(false).
		SetMsg(msg).
		SetError(err).
		SetData(data)

	c.Set("result", res)
	c.Set("status", code)
	c.AbortWithStatusJSON(http.StatusOK, res)
}

// OK 通常成功数据处理
func OK(c IRespWriter, data interface{}, msg string) {

	res := NewResponse().
		SetCode(http.StatusOK).
		SetTraceID(GenerateMsgIDFromContext(c)).
		SetSuccess(true).
		SetMsg(msg).
		SetData(data)

	c.Set("result", res)
	c.Set("status", http.StatusOK)
	c.AbortWithStatusJSON(http.StatusOK, res)
}

// PageOK 分页数据处理
func PageOK(c IRespWriter, result interface{}, count int, pageIndex int, pageSize int, msg string) {

	OK(c, &PageData{
		List:     result,
		Total:    count,
		PageNum:  pageIndex,
		PageSize: pageSize,
	}, msg)
}

// Custum 兼容函数
func Custum(c IRespWriter, data gin.H) {
	data["requestId"] = GenerateMsgIDFromContext(c)
	c.Set("result", data)
	c.AbortWithStatusJSON(http.StatusOK, data)
}
